package com.bw.BaseCore.utils

import com.tencent.mmkv.MMKV
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit
import javax.inject.Singleton

@Module
@InstallIn(SingletonComponent::class)
class HttpUtil {

    @Singleton
    @Provides
    fun getRetrofit(okHttpClient: OkHttpClient):Retrofit{
        return Retrofit.Builder()
            .client(okHttpClient)
            .baseUrl("http://10.161.9.80:8886")
            .addConverterFactory(GsonConverterFactory.create())
            .build()
    }

    @Singleton
    @Provides
    fun getOkHttp():OkHttpClient{
        return  OkHttpClient.Builder()
            .writeTimeout(60, TimeUnit.SECONDS)
            .readTimeout(60, TimeUnit.SECONDS)
            .connectTimeout(60, TimeUnit.SECONDS)
            .addNetworkInterceptor(HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))
            .addInterceptor {
                var request = it.request().newBuilder()
                val token = MMKV.defaultMMKV().decodeString("Authorization","")
                if(token!=""){
                    request.addHeader("Authorization",token!!)
                }
                it.proceed(request.build())
            }
            .build()
    }



//    @Singleton
//    @Provides
//    fun retrofitProvide() : Retrofit{
//        return Retrofit.Builder()
//            .client(
//                OkHttpClient.Builder()
//                    .writeTimeout(60, TimeUnit.SECONDS)
//                    .readTimeout(60, TimeUnit.SECONDS)
//                    .connectTimeout(60, TimeUnit.SECONDS)
//                    .addInterceptor(
//                        HttpLoggingInterceptor().setLevel(
//                            HttpLoggingInterceptor.Level.BODY))
//                    .addInterceptor {
//                        var request = it.request().newBuilder()
//                        val token = MMKV.defaultMMKV().decodeString("Authorization","")
//                        if(token!=""){
//                            request.addHeader("Authorization",token!!)
//                        }
//                        it.proceed(request.build())
//                    }
//                    .build()
//            )
//            .baseUrl("http://10.161.9.80:8886")
//            .addConverterFactory(GsonConverterFactory.create())
//            .build()
//    }
}